<template>
  <div class="home-view">
    <el-card class="content-feed">
      <template #header>
        <h2>热点新闻</h2>
      </template>

<!-- 轮播图 -->
<!-- <el-carousel autoplay>
        <el-carousel-item v-for="(item, index) in carouselItems" :key="index">
          <img :src="item.image" alt="轮播图"
          style="width: 100%; height: 100%; object-fit: cover; border-radius: 5px;"   />
        </el-carousel-item>
      </el-carousel> -->

      <div class="content-list">
        <ContentCard
          v-for="item in contents"
          :key="item.contentId"
          :content="{
            id: item.contentId,
            title: item.title,
            summary: item.summary,
            author: item.username,
            publishTime: formatDate(item.publishTime),
            likeCount: item.likeCount,
            commentCount: item.commentCount,
            isLiked: item.isLiked || false,
            categoryName: item.categoryName,
            readCount: item.readCount
          }"
          @like="handleLike"
          @click="handleCardClick(item.contentId)"
          style="cursor: pointer;"
        />
      </div>

      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next"
        @current-change="handlePageChange"
        class="pagination"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import ContentCard from '@/components/ContentCard.vue'
import { getContentBaseInfo , getContentDetailInfo} from '@/api/contents' // 假设这是你的API请求方法
import { useRouter } from 'vue-router'; // 引入路由钩子函数
const router = useRouter(); // 获取路由对象

const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const contents = ref([])

// 获取内容列表
const fetchContents = async () => {
  try {
    const res = await getContentBaseInfo({
      current: currentPage.value,
      size: pageSize.value
    })
    console.log(res.data.data.contentsPage)
    contents.value = res.data.data.contentsPage.records
    total.value = res.data.data.contentsPage.total
  } catch (error) {
    console.error('获取内容列表失败:', error)
  }
}
 // 处理卡片点击事件
 const handleCardClick = (contentId) => {
  console.log("点击了卡片：", contentId);
      // 方法一：使用命名路由跳转（推荐方式）
      // router.push({
      //   name: 'ContentDetail', // 目标页面的路由名称
      //   params: { id: contentId } // 传递ID参数
      // });
      // 或者方法二：使用路径跳转
      router.push(`/content/${contentId}`);
    };


// 修改后的轮播图配置
const carouselItems = ref([
  { image: '/images/headline1.jpg' },
  { image: '/images/headline2.jpg' },
  { image: '/images/headline3.jpg' },
  { image: '/images/headline4.jpg' },
  { image: '/images/headline5.jpg' }
])


// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString()
}

// 处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page
  fetchContents()
}

// 处理点赞
const handleLike = async (contentId) => {
  try {
    const content = contents.value.find(c => c.contentId === contentId)
    if (content) {
      // 这里应该调用点赞API
      // await likeContent(contentId)

      // 模拟点赞成功后的状态更新
      content.likeCount += content.isLiked ? -1 : 1
      content.isLiked = !content.isLiked
    }
  } catch (error) {
    console.error('点赞操作失败:', error)
  }
}



// 初始化加载数据
onMounted(() => {
  fetchContents()
})
</script>

<style scoped>
.home-view {
  flex: 1;
}

.content-feed {
  margin-bottom: 20px;
}

.content-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.pagination {
  margin-top: 20px;
  justify-content: center;
}
</style>




